package com.hzit.seckill.controller;

import com.ruoyi.common.core.domain.R;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@RestController
@Slf4j
public class SempController {
	@Autowired
	private RedissonClient redissonClient;

	//1. 向连接池中放连接
	@GetMapping("/pool/put")
	public R putPool(){
		RSemaphore semaphore = redissonClient.getSemaphore("pool-lock");
		semaphore.trySetPermits(10);
		return R.ok();
	}
	//2. 消费连接
	@GetMapping("/pool/get")
	public R getPool() throws InterruptedException {
		RSemaphore semaphore = redissonClient.getSemaphore("pool-lock");
		//2.1 阻塞式的，只要放的10取完了，就处理阻塞状态
		// semaphore.acquire();
		//2.2 非阻塞式方法，如果可取值就返回true, 否则，返回false
		boolean b = semaphore.tryAcquire();
		if(b){
			log.info("正在取得资源的值。");
		}
		return R.ok();
	}
	//3. 释放一个连接
	@GetMapping("/pool/reas")
	public R poolReas(){
		RSemaphore semaphore = redissonClient.getSemaphore("pool-lock");
		semaphore.release();
		return R.ok();
	}
}
